<template>
  <div class="chart-area">
    <div class="type-options">
      <span class="type-title">图表类型：</span>
      <div class="type-list">
        <el-button v-for="(chart, index) in currentChartData" :key="chart.name" type="primary" size="small" :class="{ 'button-active': currentChartName === chart.name }" plain @click="currentChartName = chart.name;currentChartIndex = index;changeCharts(chart);">{{ chart.name }}</el-button>
      </div>
    </div>
    <div class="chart-tool">
      <el-button type="primary" class="btn" size="small" plain :class="{ 'button-active': lineChartType === 0 }" @click="onShowChart(0, splitLineChartData)">分</el-button>
      <el-button type="primary" class="btn" size="small" plain :class="{ 'button-active': lineChartType === 1 }" @click="onShowChart(1, lineChartData)">总</el-button>
    </div>
    <div
      id="publicChart"
      ref="chartParent"
      :style="{ minWith: '300px', minHeight: '400px' }"
    />
  </div>
</template>

<script>
import { formatThousands } from '@/utils/tools';
const Echarts = require('echarts/lib/echarts');
// 引入折线图
require('echarts/lib/chart/line');
// 引入提示框和标题组件
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
require('echarts/lib/component/legend');
require('echarts/lib/component/legendScroll');

export default {
  name: 'Charts',
  props: {
    // 显示的图表数据
    chartData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 显示的总线图表数据
    lineChartData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 显示的分线图表数据
    splitLineChartData: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  inject: ['getTableHeight'],
  data() {
    return {
      currentChartData: [], // 当前显示的图表数据
      currentChart: null, // 当前图表
      currentChartName: '', // 当前显示的图表名称
      currentChartIndex: 0, // 当前显示的图表索引
      copyOption: '', // 保存原始option配置
      lineChartType: 0, // 显示的图表类型 分线：0，总线：1
      option: {
        title: {
          text: '' // 标题
        },
        tooltip: {
          trigger: 'axis',
          formatter(params) {
            var res = params[0].name;
            for (var i = 0; i < params.length; i++) {
              res +=
                '<br>' +
                params[i].marker +
                params[i].seriesName +
                '：' +
                params[i].data.show;
            }
            return res;
          }
        },
        legend: {
          type: 'scroll',
          width: 700,
          itemHeight: 16,
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          splitLine: { // 网格线
            show: false
          },
          data: []
        },
        yAxis: {},
        series: [],
        color: ['#35A2DA', '#FFDB5C', '#FF0400', '#EF3CFF', '#34E31F', '#FF9FE8', '#0A0066', '#A8FFC6', '#5C20FF', '#45243D', '#BC8FFF', '#C28853', '#9C9B9F', '#0F370E']
      } // 图表配置项
    };
  },
  computed: {
    tableHeight() {
      return this.getTableHeight();
    }
  },
  watch: {
    tableHeight(val) {
      // console.log(val);
      const chartWidth = this.$refs.chartParent.clientWidth;
      this.currentChart.resize({
        width: chartWidth,
        height: val - 40
      });
    }
  },
  mounted() {
    this.currentChart = Echarts.init(document.getElementById('publicChart'));
    this.currentChart.setOption(this.option);
    this.copyOption = JSON.parse(JSON.stringify(this.option));
    this.resetFirstChart();
  },
  methods: {
    // 重置图表为第一个
    resetFirstChart() {
      this.currentChart.clear();
      this.currentChart.setOption(this.copyOption);
      this.currentChartData = this.chartData;
      this.lineChartType = 0;
      this.currentChartName = this.chartData[0].name;
      this.currentChartIndex = 0;
    },
    // 切换图表数据
    changeCharts(chart) {
      if (!chart || !chart.series) {
        this.currentChart.clear();
        this.currentChart.setOption(this.copyOption);
        return;
      }
      this.option.legend.data = chart.series.map((item) => item.name);
      this.handleTootip(chart);
      this.switchYaxis(chart);
      [this.option.title.text, this.option.series, this.option.xAxis.data] = [
        chart.name,
        chart.series,
        chart.xAxis
      ];
      this.currentChart.clear();
      this.currentChart.setOption(this.option);
    },
    // 动态切换y坐标轴的显示单位与数量
    switchYaxis(chart) {
      let classification = [];
      chart.series.forEach((item, index) => {
        item.type = 'line';
        if (item.dataType === 2) {
          classification.push(0);
          // item.yAxisIndex = 0;
        } else {
          // item.yAxisIndex = item.dataType;
          classification.push(item.dataType);
        }
      });
      classification = Array.from(new Set(classification));
      const arr = [];
      for (let i = 0; i < classification.length; i++) {
        switch (classification[i]) {
          case 0:
            arr.push({
              type: 'value',
              axisLabel: {
                show: true,
                formatter: '{value}'
              },
              splitLine: { // 网格线
                show: false
              }
            });
            break;
          case 1:
            arr.push({
              type: 'value',
              axisLabel: {
                show: true,
                formatter: '{value} %'
              },
              splitLine: { // 网格线
                show: false
              }
            });
            break;
          default:
            break;
        }
      }
      this.option.yAxis = arr;
    },
    // 提示框格式化
    handleTootip(chart) {
      chart.series.forEach((item, index) => {
        /**
         * dataType: 0 数值，1 百分数，2 金额
         * dataFormatType: 0 常规，1 保留一位小数
         */
        // if (index === 1) {
        //   item.itemStyle = {
        //     normal: {
        //       color: '#5D80F7',
        //       lineStyle: {
        //         color: '#5D80F7'
        //       }
        //     }
        //   };
        // }
        if (item.formatFinish) {
          return;
        }
        if (item.dataType === 0 && item.dataFormatType === 0) {
          item.data = item.data.map((i) => {
            return (i = {
              value: i,
              show: i
            });
          });
        } else if (item.dataType === 0 && item.dataFormatType === 1) {
          item.data = item.data.map((i) => {
            return (i = {
              value: i === null ? undefined : i,
              show: i === null ? '-' : i.toFixed(1)
            });
          });
        } else if (item.dataType === 1) {
          item.data = item.data.map((i) => {
            return (i = {
              value: i === null ? undefined : i,
              show: i === null ? '-' : i.toFixed(1) + '%'
            });
          });
        } else if (item.dataType === 2) {
          if (item.dataFormatType === 1) {
            item.data = item.data.map((i) => {
              return (i = {
                value: i === null ? undefined : i,
                show: i === null ? '-' : formatThousands(i.toFixed(1))
              });
            });
          } else {
            item.data = item.data.map((i) => {
              return (i = {
                value: i === null ? undefined : i,
                show: i === null ? '-' : formatThousands(i)
              });
            });
          }
        }
        item.formatFinish = true;
      });
    },
    // 切换分总线展示
    onShowChart(type, data = [], isForceDo = false) {
      if (this.lineChartType !== type || isForceDo) {
        if (data.length > 0) {
          this.currentChartData = data;
        } else {
          this.currentChartData = this.chartData;
        }
      }
      this.lineChartType = type;
      this.changeCharts(data[this.currentChartIndex]);
    }
  }
};
</script>

<style lang="scss" scoped>
.button-active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}
.type-options {
  margin: 20px 0 20px;
  display: flex;
  align-items: center;
  .type-list {
    flex: 1;
    flex-grow: 1;
  }
}
.type-title {
  font-size: 14px;
  color: #606266;
}
.chart-area {
  position: relative;
}
.chart-tool {
  position: absolute;
  right: 0;
  top: 61px;
  z-index: 100;
}
</style>

